package term

import (
	"context"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/service/attachment/model"
	"mall/service/attachment/rpc/internal/svc"
	"mall/service/attachment/rpc/internal/utils"
	"mall/service/attachment/rpc/internal/utils/errorhandler"
	"mall/service/attachment/rpc/types/attachment"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendCreateTermLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendCreateTermLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendCreateTermLogic {
	return &BackendCreateTermLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendCreateTermLogic) BackendCreateTerm(in *attachment.TermInfo) (*attachment.BaseIDResp, error) {
	var term model.AttachmentTerm
	var taxonomy int32
	if in.Taxonomy != nil {
		taxonomy = utils.ParseTaxonomy(strings.TrimSpace(*in.Taxonomy))
	}
	if taxonomy > 0 {
		term.Taxonomy = uint16(taxonomy)
	} else {
		term.Taxonomy = uint16(globalkey.TermTaxonomyCategory)
	}
	if in.Name != nil {
		term.Name = strings.TrimSpace(*in.Name)

		if len(term.Name) == 0 {
			return nil, errorx.NewInvalidArgumentError("term.nameRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.AttachmentTermColumns.Name] = map[string][]any{
			"equalTo": []any{term.Name},
		}
		filterMap[model.AttachmentTermColumns.Taxonomy] = map[string][]any{
			"equalTo": []any{term.Taxonomy},
		}
		_, count, err := l.svcCtx.MediaTerm.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("term.nameAlreadyExists")
		}
	}
	if in.Slug != nil {
		term.Slug = strings.TrimSpace(*in.Slug)
	}
	if in.ParentId != nil {
		term.ParentID = *in.ParentId
	}
	if in.GroupId != nil {
		term.TermGroup = uint16(*in.GroupId)
	}
	if in.Desc != nil {
		term.Description = strings.TrimSpace(*in.Desc)
	}
	if in.FilteredDesc != nil {
		term.DescriptionFiltered = strings.TrimSpace(*in.FilteredDesc)
	}
	if in.Sort != nil {
		term.Sort = uint16(*in.Sort)
	} else {
		term.Sort = uint16(9999)
	}
	if in.Status != nil {
		term.Status = uint8(*in.Status)
	} else {
		term.Status = uint8(globalkey.StatusEnabled)
	}
	now := time.Now()
	term.CreatedAt = now
	term.UpdatedAt = now
	rel := &model.AttachmentTermRel{}
	if len(in.Meta) > 0 {
		for _, m := range in.Meta {
			if m.Key == nil || len(strings.TrimSpace(*m.Key)) == 0 {
				continue
			}

			if m.Value == nil || len(strings.TrimSpace(*m.Value)) == 0 {
				continue
			}

			rel.Meta = append(rel.Meta, &model.AttachmentTermMetum{
				MetaKey:   strings.TrimSpace(*m.Key),
				MetaValue: null.StringFrom(strings.TrimSpace(*m.Value)),
			})
		}
	}
	err := l.svcCtx.MediaTerm.Insert(l.ctx, nil, &term, rel)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &attachment.BaseIDResp{
		Id:  term.TermID,
		Msg: i18n.CreateSuccess,
	}, nil
}
